﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Openfree.Framework.Common;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public partial class ShopOnlineAdmin_ProductEdit : BaseUserControl
{
    public ProductCategoryAccess productCategoryAccess;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TabsMenuItem[] listItem = new TabsMenuItem[8];
            listItem[0] = new TabsMenuItem();
            listItem[0].Text = "产品基本信息";
            listItem[0].ClientID = pnlInfo.ClientID;
            listItem[0].OnClientClick = "$('btnUpload').style.display='none'";
            listItem[1] = new TabsMenuItem();
            listItem[1].Text = "产品介绍信息";
            listItem[1].ClientID = pnlContent.ClientID;
            listItem[1].OnClientClick = "$('btnUpload').style.display=''";
            tabsMenu.TabsMenuItemArray = listItem;
            tabsMenu.CssClass = "tabsMenuA";

            InitTempVirtualFolder();
            UploadFile1.SetShowButtonClientID(btnUpload.ClientID);
            UploadFile1.SetMaxFiles(5);
            UploadFile1.SetValidExtensions("jpg,jpeg,gif,png");
            UploadFile1.SetInvalidExtensionMessage("类型错误");
            UploadFile1.SetSubject("上传图片信息");

            productCategoryAccess = new ProductCategoryAccess(base.Connection);
            IList ddlNodesIDList = productCategoryAccess.LoadListTree();
            for (int i = 0; i <= ddlNodesIDList.Count - 1; i++)
            {
                object[] obj;
                obj = (object[])ddlNodesIDList[i];
                ListItem item = new ListItem(HttpUtility.HtmlDecode((string)obj[1]), (string)obj[0]);
                ddlCategory.Items.Add(item);
            }

            hfAddOrEdit.Value = "Add";
            if (!string.IsNullOrEmpty(Request["ProductID"]))
            {
                hfAddOrEdit.Value = "Edit";
                hfID.Value = Request["ProductID"].Replace("'", string.Empty);
                InitData(Request["ProductID"]);
            }
        }
        UploadFile1.OnUploadComplete += new Controls_UploadFile_UploadFile.UploadComplete(UploadFile1_OnUploadComplete);
    }

    protected void UploadFile1_OnUploadComplete(UploadCompleteEventArgs e)
    {
        if (!UploadFile1.GetInsertEditer()) return;
        string javascript = string.Empty;
        foreach (DataRow row in e.UploadFile.Rows)
        {
            javascript += "<img src=\'" + SessionManager.UploadURL.Replace("~/", "../") + row["fileName"].ToString() + "\' /><br />";
        }

        string inbox = "<script>function insertHtml() { " +
            "var images = \"" + javascript + "\";" +
            "FTB_API[\"" + freeTextBox.ClientID + "\"].InsertHtml(images);}" +
        "setTimeout('insertHtml()', 1000);</script>";

        //inbox = string.Format(inbox, );
        Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, inbox);
    }

    private string TempVirtualFolder
    {
        get
        {
            return freeTextBox.ImageGalleryPath;
        }
    }


    private void InitTempVirtualFolder()
    {
        string folderName = System.DateTime.Now.ToString("yyMMdd") + "-" + Guid.NewGuid().ToString();
        //Response.Write("SessionManager.TempVirtualFolder" + SessionManager.TempVirtualFolder +"<br/>");                
        freeTextBox.ImageGalleryPath = "~/Temp/" + folderName;
        //更新 UploadFile1 上传文件路径， UploadStreamProvider 能够主动读取
        SessionManager.UploadURL = "~/Temp/" + folderName;
    }

    private void InitData(string productID)
    {
        DataSet ds = ProductAccess.GetDataSet(hfID.Value);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            DataRow row = ds.Tables[0].Rows[0];
            string imageGalleryPath = StoreLocationAccess.GetResourceURL(row["StoreLocationID"].ToString(),
                System.Convert.ToDateTime(row["CreateDate"].ToString()), productID);
            //fix 路径不存在,插入图片页面报错
            //   ../ 是为了去掉SiteAdmin路径
            if (!Directory.Exists(Server.MapPath("../" + imageGalleryPath)))
            {
                Directory.CreateDirectory(Server.MapPath("../" + imageGalleryPath));
            }
            freeTextBox.ImageGalleryPath = "../" + imageGalleryPath;
            //更新 UploadFile1 上传文件路径， UploadStreamProvider 能够主动读取
            SessionManager.UploadURL = "~/" + imageGalleryPath;

            tbProductCode.Text = row["ProductCode"].ToString();
            ddlCategory.SelectByValue = row["CategoryID"].ToString();            
            tbSubject.Text = row["Subject"].ToString();
            tbTaobaoURL.Text = row["TaobaoURL"].ToString();
            //tbEndDate.Text = row["EndDate"].ToString();
            //tbStandardCost.Text = row["StandardCost"].ToString();
            tbListPrice.Text = row["ListPrice"].ToString();
            //tbPromotionalPrice.Text = row["PromotionalPrice"].ToString();
            tbFreightCost.Text = row["FreightCost"].ToString();
            //tbSalesCount.Text = row["SalesCount"].ToString();
            tbInventory.Text = row["Inventory"].ToString();
            cbAllowFeedback.Value = row["AllowFeedback"].ToString();
            cbPublished.Value = row["Published"].ToString();
            tbTag.Text = row["Tag"].ToString();
            freeTextBox.Text = row["Description"].ToString();
            //   ../ 是为了去掉SiteAdmin路径
            //freeTextBox.Text = freeTextBox.Text.Replace("../" + imageGalleryPath,
            //    imageGalleryPath);
            freeTextBox.Text = freeTextBox.Text.Replace(imageGalleryPath,
                "../" + imageGalleryPath);
            imgProduct.ImageUrl = "../" + imageGalleryPath + "/" + ProductImageAccess.GetThumbImageFileName(productID);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hfAddOrEdit.Value == "Edit")
        {
            string documentID = hfID.Value;
            DataSet ds = ProductAccess.GetDataSet(documentID);
            DataRow row = ds.Tables[0].Rows[0];
            if (row["ProductCode"].ToString() != tbProductCode.Text.Trim())
            {
                if (ProductAccess.ValidateProductCode(documentID, tbProductCode.Text.Trim()))
                {
                    base.Alert("产品编号存在冲突，请重新输入");
                    return;
                }
            }

            productCategoryAccess = new ProductCategoryAccess(base.Connection);
            string oldLocationID = productCategoryAccess.GetStoreLocationID(row["CategoryID"].ToString());
            string newLocationID = productCategoryAccess.GetStoreLocationID(ddlCategory.SelectedValue);
            string oldURL = StoreLocationAccess.GetResourceURL(oldLocationID,
                System.Convert.ToDateTime(row["CreateDate"].ToString()), documentID);
            string newURL = StoreLocationAccess.GetResourceURL(newLocationID,
                System.Convert.ToDateTime(row["CreateDate"].ToString()), documentID);
            //../image/2008/03/05/bd60c1ed-2042-49ac-bc29-06d6824364c8/profile_arrow.jpg
            string htmlCode = freeTextBox.Text.Replace("../" + oldURL, newURL);
            //http://localhost:3489/WebSite/image/2008/03/05/bd60c1ed-2042-49ac-bc29-06d6824364c8/profile_arrow.jpg
            htmlCode = htmlCode.Replace(ApplicationPath + "/" + oldURL, newURL);


            string oldFullPath = StoreLocationAccess.CreateLocalResourceDirectory(oldLocationID, DateTime.Now, documentID);
            string newFullPath = StoreLocationAccess.CreateLocalResourceDirectory(newLocationID, DateTime.Now, documentID);
            if (!string.IsNullOrEmpty(tbHotImageFileName.Text))
            {

                if (tbHotImageFileName.Text.ToLower().IndexOf(".gif") > -1 ||
                    tbHotImageFileName.Text.ToLower().IndexOf(".jpg") > -1 ||
                    tbHotImageFileName.Text.ToLower().IndexOf(".bmp") > -1 ||
                    tbHotImageFileName.Text.ToLower().IndexOf(".png") > -1)
                {
                    string largeImageFileName = oldFullPath + "\\" + 
                        tbHotImageFileName.Text;
                    string thumbImageFileName = oldFullPath +
                        documentID.Remove(documentID.IndexOf('-')) + "Thumb" +
                        tbHotImageFileName.Text.Substring(tbHotImageFileName.Text.LastIndexOf('.'));
                    try
                    {
                        //修改只修改了图片，文件名没有变化，不需要更新数据库
                        File.Delete(thumbImageFileName);
                        
                        CreateThumbnailImage(largeImageFileName, thumbImageFileName, 140, 105);
                        imgProduct.ImageUrl = "../" + newURL + "/" +
                            documentID.Remove(documentID.IndexOf('-')) + "Thumb" +
                            tbHotImageFileName.Text.Substring(tbHotImageFileName.Text.LastIndexOf('.'));

                        DataSet dsImage = ProductImageAccess.GetDataSet(documentID, "index");
                        if (dsImage.Tables[0].Rows.Count > 0)
                        {
                            DataRow rowImage = dsImage.Tables[0].Rows[0];
                            rowImage["ThumbImageFileName"] = thumbImageFileName.Substring(thumbImageFileName.LastIndexOf('\\') + 1);
                            rowImage["LargeImageFileName"] = largeImageFileName.Substring(largeImageFileName.LastIndexOf('\\') + 1);
                            BaseAccess.UpdateDataSet(base.Connection, "T_ProductImage", dsImage);
                        }
                        else
                        {
                            DataRow rowImage = dsImage.Tables[0].NewRow();
                            rowImage["ThumbImageFileName"] = thumbImageFileName.Substring(thumbImageFileName.LastIndexOf('\\') + 1);
                            rowImage["LargeImageFileName"] = largeImageFileName.Substring(largeImageFileName.LastIndexOf('\\') + 1);
                            dsImage.Tables[0].Rows.Add(rowImage);
                            BaseAccess.UpdateDataSet(base.Connection, "T_ProductImage", dsImage);
                        }
                    }
                    catch (Exception ex)
                    {
                        base.Alert("创建缩略图失败:" + ex.Message);
                        return;
                    }
                }
                else
                {
                    base.Alert("无效的图片格式");
                    return;
                }
            }
            if (oldFullPath != newFullPath)
            {
                DirectoryManager.CopyDirectory(oldFullPath, newFullPath);
                DirectoryManager.DeleteDirectory(oldFullPath);
            }

            row["ProductCode"] = tbProductCode.Text.Trim();
            row["CategoryID"] = ddlCategory.SelectedValue;
            row["StoreLocationID"] = newLocationID;
            row["Subject"] = tbSubject.Text.Trim();
            row["Description"] = htmlCode;
            //row["EndDate"] = tbEndDate.Text;
            //row["StandardCost"] = tbStandardCost.Value;
            row["ListPrice"] = tbListPrice.Value;
            //row["PromotionalPrice"] = tbPromotionalPrice.Value;
            row["FreightCost"] = tbFreightCost.Text;
            //row["SalesCount"] = tbSalesCount.Value;
            row["Inventory"] = tbInventory.Value;
            row["Published"] = cbPublished.Checked;
            row["AllowFeedback"] = cbAllowFeedback.Checked;
            row["Tag"] = tbTag.Text;
            row["TaobaoURL"] = tbTaobaoURL.Text;
            BaseAccess.UpdateDataSet(base.Connection, "T_Product", ds);
        }
        else
        {
            string documentID = Guid.NewGuid().ToString();
            string productCode = tbProductCode.Text.Trim();
            if (ProductAccess.ValidateProductCode(productCode))
            {
                base.Alert("产品编号存在冲突，请重新输入");
                return;
            }

            if (!string.IsNullOrEmpty(tbHotImageFileName.Text))
            {


                if (tbHotImageFileName.Text.ToLower().IndexOf(".gif") > -1 ||
                    tbHotImageFileName.Text.ToLower().IndexOf(".jpg") > -1 ||
                    tbHotImageFileName.Text.ToLower().IndexOf(".bmp") > -1 ||
                    tbHotImageFileName.Text.ToLower().IndexOf(".png") > -1)
                {
                    string largeImageFileName = Server.MapPath(TempVirtualFolder) + "\\" +
                        tbHotImageFileName.Text;
                    string thumbImageFileName = Server.MapPath(TempVirtualFolder) + "\\" +
                        documentID.Remove(documentID.IndexOf('-')) + "Thumb" +
                        tbHotImageFileName.Text.Substring(tbHotImageFileName.Text.LastIndexOf('.'));
                    try
                    {
                        
                        CreateThumbnailImage(largeImageFileName, thumbImageFileName, 200, 230);
                        DataSet dsImage = ProductImageAccess.GetEmptyDataSet();
                        DataRow rowImage = dsImage.Tables[0].NewRow();
                        rowImage["ProductImageID"] = Guid.NewGuid().ToString();
                        rowImage["ProductID"] = documentID;
                        rowImage["Category"] = "index";
                        rowImage["ThumbImageFileName"] = thumbImageFileName.Substring(thumbImageFileName.LastIndexOf('\\') + 1);
                        rowImage["LargeImageFileName"] = largeImageFileName.Substring(largeImageFileName.LastIndexOf('\\') + 1);
                        dsImage.Tables[0].Rows.Add(rowImage);
                        BaseAccess.UpdateDataSet(base.Connection, "T_ProductImage", dsImage);
                    }
                    catch (Exception ex)
                    {
                        base.Alert("创建缩略图失败:" + ex.Message);
                        return;
                    }
                }
                else
                {
                    base.Alert("无效的图片格式");
                    return;
                }
            }
            productCategoryAccess = new ProductCategoryAccess(base.Connection);
            string storeLocationID = productCategoryAccess.GetStoreLocationID(ddlCategory.SelectedValue);
            DataSet ds = ProductAccess.GetEmptyDataSet();
            DataRow row = ds.Tables[0].NewRow();

            // tempURL              /WebSite/Temp/070822-63d51050-ccb7-431c-bdac-4353bb1c90b9
            // documentURL          Document/2007/08/22/7fe74420-533b-42fc-9eb9-b8fd3dd68242
            // documentFullPath     C:\Document\2007\08\22\7fe74420-533b-42fc-9eb9-b8fd3dd68242
            // src Http://localhost:8080/WebSite/....
            // src Document/2007/08/22/7fe74420-533b-42fc-9eb9-b8fd3dd68242/ME3.JPG        

            string tempURL = ApplicationPath + TempVirtualFolder.Replace("~", string.Empty);
            string documentURL = StoreLocationAccess.GetResourceURL(storeLocationID, DateTime.Now, documentID);
            string documentFullPath = StoreLocationAccess.CreateLocalResourceDirectory(storeLocationID, DateTime.Now, documentID);
            string htmlCode = freeTextBox.Text;
            htmlCode = htmlCode.Replace(tempURL, documentURL);
            htmlCode = htmlCode.Replace(ApplicationPath + "/" + documentURL, documentURL);
            DirectoryManager.CopyDirectory(Server.MapPath(tempURL), documentFullPath);
            //在calta的服务器上 SessionManager.TempVirtualFolder 会重复赋值，不知道什么原因
            //Response.Write("SessionManager.TempVirtualFolder" + SessionManager.TempVirtualFolder + "<br/>");



            row["ProductID"] = documentID;
            row["ProductCode"] = productCode;
            row["CategoryID"] = ddlCategory.SelectedValue;
            row["StoreLocationID"] = storeLocationID;
            row["Subject"] = tbSubject.Text.Trim();
            row["Description"] = htmlCode;
            row["CreateDate"] = DateTime.Now.ToString();
            //if (!string.IsNullOrEmpty(tbEndDate.Text))
            {
                row["EndDate"] = DateTime.Now.ToString(); //tbEndDate.Text;//本期结束时间
            }
            row["StandardCost"] = 0;// tbStandardCost.Value;//成本价格
            row["ListPrice"] = tbListPrice.Value;
            row["PromotionalPrice"] = 0;// tbPromotionalPrice.Value;//促销价格
            row["FreightCost"] = tbFreightCost.Text;
            row["SalesCount"] = 0;// tbSalesCount.Value;//销售数量
            row["Inventory"] = tbInventory.Value;
            row["Published"] = cbPublished.Checked;
            row["AllowFeedback"] = cbAllowFeedback.Checked;
            row["TaobaoURL"] = tbTaobaoURL.Text;
            row["ViewCount"] = 0;
            row["GoodCount"] = 0;
            row["BadCount"] = 0;
            row["Tag"] = tbTag.Text;

            ds.Tables[0].Rows.Add(row);
            BaseAccess.UpdateDataSet(base.Connection, "T_Product", ds);
            tbSubject.Text = string.Empty;
            //tbStandardCost.Text = string.Empty;
            tbListPrice.Text = string.Empty;
            //tbPromotionalPrice.Text = string.Empty;
            //tbSalesCount.Text = string.Empty;
            tbInventory.Text = string.Empty;
            tbTag.Text = string.Empty;
            freeTextBox.Text = string.Empty;
        }

        InitTempVirtualFolder();
        base.Alert("保存成功");
    }

    public static bool CreateThumbnailImage(string sourceFileName, string targetFileName, int width, int height)
    {
        try
        {
            Bitmap image = new Bitmap(sourceFileName);
            int newHeight = 0;
            int newWidth = 0;
            if (image.Size.Width >= image.Size.Height)
            {
                int temp = System.Convert.ToInt32(image.Size.Height * (System.Convert.ToDouble(image.Size.Width - width) / image.Size.Width));
                newWidth = width;
                newHeight = image.Size.Height - temp;
                if (newHeight > height)
                {
                    temp = System.Convert.ToInt32(image.Size.Width * (System.Convert.ToDouble(image.Size.Height - height) / image.Size.Height));
                    newWidth = image.Size.Width - temp;
                    newHeight = height;
                }
            }
            else if (image.Size.Width < image.Size.Height)
            {
                int temp = System.Convert.ToInt32(image.Size.Width * (System.Convert.ToDouble(image.Size.Height - height) / image.Size.Height));
                newWidth = image.Size.Width - temp;
                newHeight = height;
                if (newWidth > width)
                {
                    temp = System.Convert.ToInt32(image.Size.Height * (System.Convert.ToDouble(image.Size.Width - width) / image.Size.Width));
                    newWidth = width;
                    newHeight = image.Size.Height - temp;
                }
            }

            if (newHeight == 0)
            {
                newHeight = image.Height;
            }
            if (newWidth == 0)
            {
                newWidth = image.Width;
            }

            //低质量的缩略图
            //System.Drawing.Image newImage = image.GetThumbnailImage(newWidth, newHeight, null, new System.IntPtr());
            //newImage.Save(targetFileName, System.Drawing.Imaging.ImageFormat.Jpeg);

            Bitmap newImage = new Bitmap(newWidth, newHeight);
            //设置画布的描绘质量
            Graphics g = Graphics.FromImage(newImage);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(image, new Rectangle(0, 0, newWidth, newHeight),
                0, 0, image.Width, image.Height, GraphicsUnit.Pixel);
            g.Dispose();
            //以下代码为保存图片时,设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();
            EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, new long[]{100});
            encoderParams.Param[0] = encoderParam;
            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo对象
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    //设置JPEG编码
                    jpegICI = arrayICI[x];                    
                    break;
                }
            }
            if (jpegICI != null)
            {
                newImage.Save(targetFileName, jpegICI, encoderParams);
            }
            else
            {
                newImage.Save(targetFileName, image.RawFormat);
            }
            image.Dispose();
            newImage.Dispose();
            return true;
        }
        catch
        {
            return false;
        }
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        freeTextBox.Text = string.Empty;
    }
}